package com.ruoyi.web.controller.invoice;

import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGetJsapiTicketRequest;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGetJsapiTicketResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.auth.LoginType;
import com.ruoyi.framework.shiro.auth.UserToken;
import com.ruoyi.system.domain.SysAuthUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.impl.CorpTokenService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 第三方企业应用免登
 *
 * @author openapi@dingtalk
 * 2020-11-3
 */
@RestController
@RequestMapping("/invoice")
public class DingLoginController {

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 欢迎页面，通过 /welcome 访问，判断后端服务是否启动
     *
     * @return 字符串 welcome
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "welcome";
    }


    @Autowired
    private CorpTokenService corpTokenService;


    public AjaxResult jsticket(@RequestParam("corpId") String corpId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
        OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
        req.setHttpMethod("GET");
        String access_token = null;
        try {
            access_token = corpTokenService.getCorpToken(corpId);
            OapiGetJsapiTicketResponse rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
            if (rsp.isSuccess()) {
                Map<String, String> rMap = new HashMap<>();
                rMap.put("ticket", rsp.getTicket());
                rMap.put("expireIn", rsp.getExpiresIn() + "");
                return AjaxResult.success(rsp.getTicket());
            }
            return AjaxResult.error(rsp.getErrmsg());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * @param requestAuthCode
     * @return ServiceResult
     * 2020-11-3
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResult login(@RequestParam("code") String requestAuthCode, @RequestParam("corpId") String corpId) {

        // 获取access_token，注意正式代码要有异常流处理
        String access_token = null;
        try {
            access_token = corpTokenService.getCorpToken(corpId);
            // 获取用户信息
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.setCode(requestAuthCode);
            request.setHttpMethod("GET");
            OapiUserGetuserinfoResponse response;

            response = client.execute(request, access_token);

            String userId = response.getUserid();
            if (!response.isSuccess()) {
                return AjaxResult.error(response.getErrmsg(), null);
            }
            Map<String, Object> returnMap = new HashMap<String, Object>();
            returnMap.put("userId", userId);
            System.out.println(JSONObject.toJSON(response));
            return AjaxResult.success("获取用户id登录成功", returnMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return AjaxResult.error("登录失败", null);

        }
        // 查询得到当前用户的userId
        // 获得到userId之后应用应该处理应用自身的登录会话管理（session）,避免后续的业务交互（前端到应用服务端）每次都要重新获取用户身份，提升用户体验
//
//            if (SecurityUtils.getSubject() != null && SecurityUtils.getSubject().getPrincipal() != null)
//            {
//                SysUser user = userMapper.selectAuthUserByUuid(source + response.getData().getUuid());
//                if (StringUtils.isNotNull(user))
//                {
//                    return redirect("/index");
//                }
//                // 若已经登录则直接绑定系统账号
//                SysAuthUser authUser = new SysAuthUser();
//                authUser.setAvatar(response.getData().getAvatar());
//                authUser.setUuid(source + response.getData().getUuid());
//                authUser.setUserId(ShiroUtils.getUserId());
//                authUser.setUserName(response.getData().getNickname());
//                authUser.setLoginName(response.getData().getUsername());
//                authUser.setEmail(response.getData().getEmail());
//                authUser.setSource(source);
//                userMapper.insertAuthUser(authUser);
//                return redirect("/index");
//            }
//            SysUser user = userMapper.selectAuthUserByUuid(source + response.getData().getUuid());
//            if (StringUtils.isNotNull(user))
//            {
//                Subject subject = SecurityUtils.getSubject();
//                UserToken token = new UserToken(user.getLoginName(), LoginType.NOPASSWD);
//                subject.login(token);
//                return redirect("/index");
//            }
//            else
//            {
//                return new ModelAndView("error/bind");
//            }

    }
}